package com.zyc.studentstudy.utils

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.Window
import android.view.inputmethod.InputMethodManager

object InputMethodUtil {

    @JvmStatic
    fun getInputMethodManager(context: Activity): InputMethodManager {
        return context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    }

    @JvmStatic
    fun showSoftInput(context: Activity) {
        showSoftInput(context, null)
    }

    @JvmStatic
    fun showSoftInput(context: Activity, view: View?) {
        val imm = getInputMethodManager(context)
        if (view == null) {
            imm.hideSoftInputFromWindow(
                context.currentFocus?.windowToken,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
        } else {
            view.requestFocus()
            imm.showSoftInput(view, InputMethodManager.SHOW_FORCED)
        }
    }

    @JvmStatic
    fun closeKeyBoard(context: Activity) {
        val view = context.window.peekDecorView()
        if (view != null) {
            val inputManager =
                context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

    @JvmStatic
    fun closeKeyBoard(context: Context, window: Window?) {
        if (window != null) {
            val inputManager =
                context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.hideSoftInputFromWindow(window.peekDecorView().windowToken, 0)
        }
    }

    @JvmStatic
    fun hideSoftInputFromWindow(context: Activity, view: View) {
        view.clearFocus()
        val imm = getInputMethodManager(context)
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }
}